from deepseek_api import DeepseekAPI
import speech_recognition as sr
from pydub import AudioSegment
import io
from wxauto import WeChat

class ChatHandler:
    def __init__(self):
        self.api = DeepseekAPI()
        self.recognizer = sr.Recognizer()
        self.wx = WeChat()
    
    def handle_message(self, msg_type, content, sender):
        """处理消息并返回简洁的回复"""
        try:
            current_msg = str(content)
            
            # 打印调试信息
            print(f"收到消息: {current_msg}")
            
            # 如果是AI的回复（即本程序发出的消息），不处理
            if current_msg.startswith("AI：") or current_msg.startswith("在忙"):
                print("这是AI的回复，跳过处理")
                return None
            
            # 处理用户消息
            if msg_type == "text":
                response = self.api.chat(current_msg)
                return response
            elif msg_type == "voice":
                text = self.voice_to_text(content)
                if text:
                    response = self.api.chat(text)
                    return response
                return "抱歉，我没有听清楚"
            else:
                return "请用文字告诉我您的问题"
            
        except Exception as e:
            print(f"处理消息时发生错误：{str(e)}")
            return None
    
    def handle_text(self, content):
        """处理文本消息"""
        response = self.api.chat(content)
        return response
    
    def handle_image(self, content):
        """处理图片消息"""
        return "我看到了您发送的图片，请问有什么可以帮您的吗？"
    
    def handle_voice(self, content):
        """处理语音消息"""
        return "我听到了您的语音消息，请问有什么可以帮您的吗？"
    
    def handle_video(self, content):
        """处理视频消息"""
        return "我看到了您发送的视频，请问有什么可以帮您的吗？"
    
    def handle_file(self, content):
        """处理文件消息"""
        return "我收到了您发送的文件，请问有什么可以帮您的吗？"
    
    def handle_url(self, content):
        """处理链接消息"""
        return "我看到了您分享的链接，请问有什么可以帮您的吗？"
    
    def voice_to_text(self, voice_content):
        """将语音转换为文字"""
        try:
            # 假设voice_content是语音文件的二进制数据
            audio = AudioSegment.from_file(io.BytesIO(voice_content))
            
            # 转换为wav格式
            wav_data = io.BytesIO()
            audio.export(wav_data, format="wav")
            wav_data.seek(0)
            
            # 使用speech_recognition进行识别
            with sr.AudioFile(wav_data) as source:
                audio_data = self.recognizer.record(source)
                text = self.recognizer.recognize_google(audio_data, language='zh-CN')
                return text
                
        except Exception as e:
            print(f"语音转文字失败：{str(e)}")
            return None 